package com.yueya.api.menu;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.yueya.basic.menu.Menu;
import com.yueya.common.constant.CodeConst;
import com.yueya.common.model.Resp;
import com.yueya.common.service.BaseService;

import net.sf.json.JSONObject;

public class IMenuService extends BaseService {

	// 获取菜单
	public Resp getMenu(JSONObject json, String userId) {
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("userid", userId);
		String menus1Sql = " select * from t_menu a  join (select  c.parent_id   from t_role_user a join t_role_menu b on a.role_id=b.role_id join t_menu c on c.id=b.menu_id where   (a.user_id='"
				+ userId
				+ "' or exists (select 1 from t_role where is_mr='1' and id=a.role_id)) group by c.parent_id union select  c.id   from t_role_user a join t_role_menu b on a.role_id=b.role_id join t_menu c on c.id=b.menu_id where   (a.user_id='"
				+ userId
				+ "' or exists (select 1 from t_role where is_mr='1' and id=a.role_id)) group by c.id ) as b on a.id=b.parent_id where a.status='1' and a.show_level = '1' order by a.order_id asc \r\n"
				+ " ";
		List<Menu> menus1 = Menu.dao.find(menus1Sql);
		List<Menu> menus2 = Menu.service.getMenuTwoList(param);
		List<Object> list1 = new ArrayList<Object>();
		List<Object> list2 = new ArrayList<Object>();
		Menu menu1 = null;
		Menu menu2 = null;
		Map<String, Object> m1 = null;
		Map<String, String> m2 = null;
		if (menus1.size() > 0 & menus2.size() > 0) {
			for (int i = 0; i < menus1.size(); i++) {
				menu1 = menus1.get(i);
				m1 = new HashMap<String, Object>();
				m1.put("icon", menu1.getStr("icon"));
				m1.put("index", menu1.getStr("url") == null ? "" : menu1.getStr("url"));
				m1.put("title", menu1.getStr("name"));
				list2 = new ArrayList<Object>();
				for (int j = 0; j < menus2.size(); j++) {
					menu2 = menus2.get(j);
					if (menu1.getStr("id").equals(menu2.getStr("parent_id"))) {
						m2 = new HashMap<String, String>();
						m2.put("title", menu2.getStr("name"));
						m2.put("index", menu2.getStr("url") == null ? "" : menu2.getStr("url"));
						list2.add(m2);
					}
				}
				if (list2.size() > 0) {
					m1.put("subs", list2);
				}
				list1.add(m1);
			}
			resp.setCode(CodeConst.SUCCESS);
			resp.setData(list1);
			resp.setMsg("some menu data");
		} else {
			resp.setCode("21001");
			resp.setMsg("no menu data");
		}

		return resp;
	}

}